#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode* tmp = NULL;
    if (!head->next)
    {
        free(head);
        return NULL;
    }
    int size = 1;
    struct ListNode* phead = head;
    while (phead->next != NULL)
    {
        size++;
        phead = phead->next;
    }
    n = size - n;
    if (!n)
    {
        tmp = head->next;
        free(head);
        return tmp;
    }
    phead = head;
    while (--n)
    {
        phead = phead->next;
    }
    tmp = phead->next->next;
    free(phead->next);
    phead->next = tmp;

    //printf("%d ",size);
    return head;
}